package com.fyt.reachgo.controller;

import com.fyt.reachgo.domain.Chat;
import com.fyt.reachgo.domain.Result;
import lombok.RequiredArgsConstructor;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.util.Timeout;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ai")
@RequiredArgsConstructor
public class AiController {

    private final ChatClient chatClient;

    @Autowired
    RestTemplate restTemplate;

    @PostMapping(value = "/chat",produces = "text/event-stream")
    public Flux<String> chat(@RequestBody Chat chat) {

        String question = "现在你是一名中国专业导游AI,名字叫做：小睿，你需要以专业导游的独到视角回答我的问题，回答时请不要有特殊标点符号例如：#、@等，每个分点之间请用换行符分开：" + chat.getQuestion();
        System.out.println(question);
        // 流式输出对话
        Flux<String> response = this.chatClient.prompt()
                .user(question)
                .stream()
                .content();

        System.out.println(response);
        return response;
    }


    @PostMapping("/chat2")
    public Result chat2(@RequestBody Chat chat) {
        // 从当前请求中获取Authorization请求头
        String authorizationHeader = "sk-6596c5025697435ba7206381637c57d8";
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", authorizationHeader); // 添加Authorization请求头
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-r1"); // 设置模型
        requestBody.put("input", Map.of(
                "messages", List.of(
                        Map.of("role", "user", "content", chat.getQuestion()) // 设置用户消息
                )
        ));
        requestBody.put("parameters", Map.of("result_format", "message")); // 设置参数

        // 封装请求体和请求头
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送请求并获取响应
        String response = restTemplate.exchange(
                "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
                HttpMethod.POST,
                requestEntity,
                String.class
        ).getBody();

        return Result.success(response);
    }


    @PostMapping("/chat3")
    public Result chat3(@RequestBody Chat chat) {
        // 配置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setResponseTimeout(Timeout.ofMinutes(3)) // 读取超时 3 分钟
                .setConnectionRequestTimeout(Timeout.ofSeconds(30)) // 请求超时 30 秒
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

        // 创建 RestClient
        RestClient restClient = RestClient.builder()
                .requestFactory(factory)
                .build();

        // 使用 RestClient 发送请求
        String question = chat.getQuestion();
        String response = restClient.post()
                .uri("https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation") // 替换为实际 API 地址
                .body(Map.of("question", question)) // 替换为实际的请求体
                .retrieve()
                .body(String.class);

        System.out.println(response);
        return Result.success(response);
    }





}
